package com.ltu.util.security;


import java.security.*;
import java.security.spec.AlgorithmParameterSpec;

import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


import org.bouncycastle.util.encoders.Base64;


import net.sf.json.JSONObject;



/**
 * 功能：AES工具类
 * @author wql
 *
 */
public class AESUtil {

    /**
     * 解密数据
     * @param encryptedData 被加密数据
     * @param sessionkey 密匙
     * @param iv 偏移量
     * @return
     */
    public static JSONObject decode(String encryptedData,String sessionkey,String iv) {
        byte[] dataByte = Base64.decode(encryptedData);
        byte[] keyByte = Base64.decode(sessionkey);
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }

            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");

                return JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    public static String wxDecrypt (String encrypted, String sessionKey, String iv)throws Exception {
        byte[] encrypData = new Base64().decode(encrypted);
        byte[] ivData = iv.getBytes();
        byte[] sKey = sessionKey.getBytes();
        String decrypt = decrypt(sKey,ivData,encrypData);
        return decrypt;
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        byte[] resultByte = cipher.doFinal(encData);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            System.out.print(result);
        }
        return new String(cipher.doFinal(encData),"UTF-8");
    }

    public static void main(String[] args) throws Exception{
        String encryptedData = "CsmF7DPiQSXL9VSw74Cf3rVdpH7yqA9lW0RR+mvsBP+i0dI/coAmOekjadtQAcbp7bIZs+hWkFCwiID3VsgCKssB8icBldmn2Z07TGrbVyYlEWPs8R7H32I4GZq7S2ISxqCNXo7frOzqf7b0qEEKp70gK5wvS2brbaQiDzh2IuQaYLnl+YOhbwcNKSVgfGcf432z5um2hwvLtv4yDb/uZw==";
        String iv = "sIE4BovuTkpugHFBH4HUkQ==";
        String session_key = "GLUyh5II1BXtYPm1jKnkbQ==";

        JSONObject wxDecrypt = decode(encryptedData, session_key, iv);

        System.out.println(wxDecrypt);
    }





}